<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
           v-if="!viewFlag"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:projectTask:add']"
        >新增</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="projectTaskList" @selection-change="handleSelectionChange">
      <el-table-column v-if="!viewFlag" type="selection" width="55" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务结束时间" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="考核指标描述" align="center" prop="assessmentCriteria" />
      <el-table-column label="考核形式" align="center" prop="assessmentForm" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">



          <el-popover
            v-if="viewFlag"
            placement="right"
            title="指标信息"
            width="1200"
            trigger="click"
          >
            <el-table
              :data="buildTreeData(scope.row.sciTaskIndicatorItemList || [])"
              row-key="id"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              default-expand-all
              border>
              <el-table-column label="层级" width="150">
                <template slot-scope="scope">
                  <span>{{ getLevelLabel(scope.row.itemLevel) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="指标名称" prop="itemName" width="300" />
              <el-table-column label="指标性质" prop="indicatorNature">
                <template slot-scope="scope">
                  <span v-if="scope.row.isDeepestLevel === 0">-</span>
                  <span v-else>{{ scope.row.indicatorNature }}</span>
                </template>
              </el-table-column>
              <el-table-column label="指标方向" prop="indicatorDirection">
                <template slot-scope="scope">
                  <span v-if="scope.row.isDeepestLevel === 0">-</span>
                  <span v-else>{{ scope.row.indicatorDirection }}</span>
                </template>
              </el-table-column>
              <el-table-column label="目标值" prop="targetValue">
                <template slot-scope="scope">
                  <span v-if="scope.row.isDeepestLevel === 0">-</span>
                  <span v-else>{{ scope.row.targetValue }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单位" prop="unit">
                <template slot-scope="scope">
                  <span v-if="scope.row.isDeepestLevel === 0">-</span>
                  <span v-else>{{ scope.row.unit }}</span>
                </template>
              </el-table-column>
              <el-table-column label="分值" prop="score">
                <template slot-scope="scope">
                  <span v-if="scope.row.isDeepestLevel === 0">-</span>
                  <span v-else>{{ scope.row.score }}</span>
                </template>
              </el-table-column>
            </el-table>

            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              slot="reference" >查看指标</el-button>
          </el-popover>


          <el-button
          v-if="!viewFlag"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:projectTask:edit']"
          >修改</el-button>
          <el-button
          v-if="!viewFlag"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:projectTask:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改项目任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-card shadow="always" style="margin: 20px;">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="form.taskName" placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker clearable
              v-model="form.startTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择任务开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker clearable
              v-model="form.endTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择任务结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考核指标描述" prop="assessmentCriteria">
            <el-input v-model="form.assessmentCriteria" type="textarea" :rows="4" placeholder="请输入考核指标描述" />
          </el-form-item>
          <el-form-item label="成果形式" prop="assessmentForm">
            <el-input v-model="form.assessmentForm"  type="textarea" :rows="4" placeholder="请输入成果形式" />
          </el-form-item>

        <el-divider content-position="center">项目产出指标项</el-divider>

        <!-- 模板选择 -->
        <el-row :gutter="20" style="margin-bottom: 15px;">
          <el-col :span="16">
            <el-form-item label="选择模板" prop="selectedTemplateId">
              <el-select
                v-model="selectedTemplateId"
                placeholder="请选择模板"
                @change="handleTemplateChange"
                style="width: 100%">
                <el-option
                  v-for="template in filteredTemplates"
                  :key="template.id"
                  :label="template.name"
                  :value="template.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div style="line-height: 40px;">
              <span v-if="maxLevel > 0">最大层级深度: {{ maxLevel }}</span>
            </div>
          </el-col>
        </el-row>

        <!-- 指标项表格 -->
        <div v-if="maxLevel > 0">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                @click="handleAddSciTaskIndicatorItem">
                添加指标项
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDeleteSciTaskIndicatorItem">
                删除指标项
              </el-button>
            </el-col>
          </el-row>

          <!-- 使用递归组件展示树形结构 -->
          <el-table
            :data="indicatorTreeData"
            row-key="itemId"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            default-expand-all
            border
            @selection-change="handleSciTaskIndicatorItemSelectionChange">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="层级" width="150" align="center">
              <template slot-scope="scope">
                <!-- 动态生成层级标签 -->
                <span>{{ getLevelLabel(scope.row.itemLevel) }}</span>
              </template>
            </el-table-column>

            <el-table-column label="指标名称" prop="itemName">
              <template slot-scope="scope">
                <div :style="{ paddingLeft: scope.row.itemLevel * 20 + 'px' }">
                  <el-input
                    v-model="scope.row.itemName"
                    placeholder="指标名称"
                    size="small" />
                </div>
              </template>
            </el-table-column>

            <!-- 仅在最深层级显示详细指标信息 -->
            <template v-if="maxLevel > 0">
              <el-table-column label="指标性质" prop="indicatorNature" width="120" v-if="showDetailColumn()">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemLevel < maxLevel">-</span>
                  <el-select
                    v-else
                    v-model="scope.row.indicatorNature"
                    placeholder="请选择"
                    size="small"
                    style="width: 100%">
                    <el-option label="正向" value="正向"></el-option>
                    <el-option label="反向" value="反向"></el-option>
                    <el-option label="定性" value="定性"></el-option>
                    <el-option label="无" value="无"></el-option>

                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="指标方向" prop="indicatorDirection" width="120" v-if="showDetailColumn()">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemLevel < maxLevel">-</span>
                  <el-select
                    v-else
                    v-model="scope.row.indicatorDirection"
                    placeholder="请选择"
                    size="small"
                    style="width: 100%">
                    <el-option label="大于" value="大于"></el-option>
                    <el-option label="小于" value="小于"></el-option>
                    <el-option label="等于" value="等于"></el-option>
                    <el-option label="大于等于" value="大于等于"></el-option>
                    <el-option label="小于等于" value="小于等于"></el-option>
                    <el-option label="定性" value="定性"></el-option>
                    <el-option label="无" value="无"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="预期目标值" prop="targetValue" width="120" v-if="showDetailColumn()">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemLevel < maxLevel">-</span>
                  <el-input
                    v-else
                    v-model="scope.row.targetValue"
                    placeholder="目标值"
                    size="small" />
                </template>
              </el-table-column>

              <el-table-column label="计量单位" prop="unit" width="120" v-if="showDetailColumn()">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemLevel < maxLevel">-</span>
                  <el-input
                    v-else
                    v-model="scope.row.unit"
                    placeholder="单位"
                    size="small" />
                </template>
              </el-table-column>

              <el-table-column label="分值" prop="score" width="120" v-if="showDetailColumn()">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemLevel < maxLevel">-</span>
                  <el-input-number
                    v-else
                    v-model="scope.row.score"
                    size="small"
                    :min="0"
                    controls-position="right"
                    style="width: 100%" />
                </template>
              </el-table-column>

              <el-table-column label="备注" prop="unit" width="200" v-if="showDetailColumn()">
                <template slot-scope="scope">
                  <span v-if="scope.row.itemLevel < maxLevel">-</span>
                  <el-input
                    v-else
                    v-model="scope.row.remark"
                    placeholder="备注"
                    size="small" />
                </template>
              </el-table-column>
            </template>

            <el-table-column label="操作" width="150" align="center">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="addChildIndicator(scope.row)"
                  v-if="scope.row.itemLevel < maxLevel">
                  添加子项
                </el-button>
                <span v-else>-</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProjectTask, getProjectTask, delProjectTask, addProjectTask, updateProjectTask } from "@/api/sci/projectTask";
import {listIndicatorTemplate} from "@/api/sci/indicatorTemplate";

export default {
  name: "ProjectTask",
  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
    viewFlag: {
      type: Boolean,
      default: false
    },
  },
    data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSciTaskIndicatorItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目任务表格数据
      projectTaskList: [],
      // 项目产出指标项表格数据
      sciTaskIndicatorItemList: [],
      // 模板列表
      templateList: [],
      // 选中的模板ID
      selectedTemplateId: null,
      // 最大层级深度
      maxLevel: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      localIdCounter: 0, // 用于生成唯一的 localId
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        projectId: this.projectId,
        taskName: null,
        startTime: null,
        endTime: null,
        assessmentCriteria: null,
        assessmentForm: null,
        status: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        isDeleted: null
      },
      // 表单参数
      form: {
        projectId: this.projectId,
      },
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "任务开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "任务结束时间不能为空", trigger: "blur" }
        ],
        assessmentCriteria: [
          { required: true, message: "考核指标描述不能为空", trigger: "blur" }
        ],
        assessmentForm: [
          { required: true, message: "考核形式不能为空", trigger: "blur" }
        ],
        // selectedTemplateId: [
        //   { required: true, message: "请选择模板", trigger: "change" }
        // ]
      }
    };
  },
  created() {
    if(this.projectId !== null){
      this.queryParams.projectId = this.projectId;
      this.getList();
    }else{
      this.loading=false;
    }
  },
  computed: {
   // 过滤后的模板（启用状态且项目类型匹配）
    filteredTemplates() {
      return this.templateList.filter(template =>
        template.enableStatus === 1 &&
        (template.projectType === '纵向' || template.projectType === '横向')
      );
    },

    // 构建树形结构的指标数据
    indicatorTreeData() {
      if (!this.sciTaskIndicatorItemList || this.sciTaskIndicatorItemList.length === 0) {
        return [];
      }

      // 创建映射以便快速查找节点
      const nodeMap = new Map();
      const roots = [];

      // 初始化所有节点，确保有children属性
      this.sciTaskIndicatorItemList.forEach(item => {
        // 如果还没有children属性，则添加
        if (!item.hasOwnProperty('children')) {
          this.$set(item, 'children', []);
        } else {
          // 清空children，因为我们要重新构建树
          item.children = [];
        }
        nodeMap.set(item.itemId, item);
      });

      // 构建父子关系
      this.sciTaskIndicatorItemList.forEach(item => {
        const parentId = item.parentId;
        if (!parentId || parentId === "0" || !nodeMap.has(parentId)) {
          roots.push(item);
        } else {
          const parent = nodeMap.get(parentId);
          if (parent) {
            parent.children.push(item);
          }
        }
      });

      return roots;
    }
  },
  watch: {
    projectId(newVal) {
      if (newVal === null) {
        this.projectTaskList = []; // 清空 projectTaskList 数组
        this.queryParams.projectId = null; // 将 queryParams.projectId 设置为 null
        this.total = 0;
        return; // 如果 projectId 为 null，不执行任何操作
      }
      // 当 projectId 变化时，更新查询参数并重新获取列表
      this.queryParams.projectId = newVal;
      this.getList();
    }
  },
     methods: {

    getLevelLabel(level) {
      // 中文数字映射（扩展到20）
      const chineseNums = [
        '零', '一', '二', '三', '四', '五'
      ];

      // 自动降级处理（超过20使用数字）
      const chineseNum = level <= 20 ? chineseNums[level] : level;

      return `${chineseNum}级指标`;
    },
    /** 查询项目任务列表 */
    getList() {
      this.loading = true;
      listProjectTask(this.queryParams).then(response => {
        this.projectTaskList = response.rows;
        this.total = response.total;


        // 遍历 taskList 并为每个任务获取子信息
        const promises = this.projectTaskList.map(task => {
          return getProjectTask(task.id).then(subResponse => {
            // 假设 subResponse.rows 是子信息数组
            task.sciTaskIndicatorItemList = [...subResponse.data.sciTaskIndicatorItemList]; // 将子信息整合到对应的任务中
          }).catch(error => {
            task.sciTaskIndicatorItemList = []; // 如果请求失败，可以赋空数组或其他默认值
          });
        });

        // 等待所有子任务请求完成
        Promise.all(promises).finally(() => {
          this.loading = false;
        });
        this.submitLocalData();


      });
    },

    // 判断是否正在编辑某一项
    isEditingItem(row) {
      // 这里可以根据需要添加编辑状态的判断逻辑
      return false;
    },

    // 判断是否显示详细列
    showDetailColumn() {
      return this.maxLevel > 0;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        localId: null,
        projectId: null,
        taskName: null,
        startTime: null,
        endTime: null,
        assessmentCriteria: null,
        assessmentForm: null,
        status: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        isDeleted: null
      };
      this.sciTaskIndicatorItemList = [];
      this.selectedTemplateId = null;
      this.maxLevel = 0;
      this.resetForm("form");
    },

     resetData() {
      this.reset();
      this.projectTaskList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目任务";
      // 加载模板列表
      this.loadTemplateList();
    },

    /** 加载模板列表 */
    async loadTemplateList() {
      try {
        const response = await listIndicatorTemplate({});
        this.templateList = response.rows || [];
      } catch (error) {
        console.error("加载模板列表失败:", error);
        this.$message.error("加载模板列表失败");
      }
    },

    /** 模板选择变更 */
    handleTemplateChange(templateId) {
      this.form.templateId = templateId; // 更新表单中的 templateId
      this.$refs.form.validateField('templateId'); // 手动触发验证
      const selectedTemplate = this.templateList.find(t => t.id === templateId);
      if (selectedTemplate) {
        this.maxLevel = selectedTemplate.maxLevel;
        this.sciTaskIndicatorItemList = [];
      } else {
        this.maxLevel = 0;
      }
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();


      // 判断 row 是否是本地任务（是否有 localId）
      if (row.localId) {
        // 是本地任务，直接填充数据
        this.form = { ...row };
        this.sciTaskIndicatorItemList = row.sciTaskIndicatorItemList || [];
        this.form.localId = row.localId; // 保留原有 localId
      } else {
        // 已提交任务，从接口获取数据
        const id = row.id || this.ids;
        getProjectTask(id).then(response => {
          this.form = response.data;
          this.sciTaskIndicatorItemList = response.data.sciTaskIndicatorItemList || [];


        });
      }

        // 加载模板列表
      this.loadTemplateList().then(() => {
        // 设置选中的模板
        if (this.sciTaskIndicatorItemList && this.sciTaskIndicatorItemList.length > 0) {
          // 这里可以根据实际情况设置默认选中的模板
          // 暂时设置为第一个启用的模板
          const firstEnabledTemplate = this.filteredTemplates[0];
          if (firstEnabledTemplate) {
            this.selectedTemplateId = firstEnabledTemplate.id;
            this.maxLevel = firstEnabledTemplate.maxLevel;
          }
        }
      });
      this.open = true;
      this.title = "修改项目任务";



      // const id = row.id || this.ids
      // getProjectTask(id).then(response => {
      //   this.form = response.data;
      //   this.sciTaskIndicatorItemList = response.data.sciTaskIndicatorItemList || [];
      //   this.open = true;
      //   this.title = "修改项目任务";
      //   // 加载模板列表
      //   this.loadTemplateList().then(() => {
      //     // 设置选中的模板
      //     if (this.sciTaskIndicatorItemList && this.sciTaskIndicatorItemList.length > 0) {
      //       // 这里可以根据实际情况设置默认选中的模板
      //       // 暂时设置为第一个启用的模板
      //       const firstEnabledTemplate = this.filteredTemplates[0];
      //       if (firstEnabledTemplate) {
      //         this.selectedTemplateId = firstEnabledTemplate.id;
      //         this.maxLevel = firstEnabledTemplate.maxLevel;
      //       }
      //     }
      //   });
      // });
    },

    /** 项目产出指标项添加按钮操作 */
   handleAddSciTaskIndicatorItem() {
      const newItem = {
        itemId: this.generateItemId(),
        templateId: this.selectedTemplateId,
        parentId: "0",
        itemName: "",
        itemLevel: 1,
        sortOrder: this.sciTaskIndicatorItemList.filter(item => item.parentId === "0").length + 1,
        isDeepestLevel: this.maxLevel === 1 ? 1 : 0,
        indicatorNature: "",
        indicatorDirection: "",
        targetValue: "",
        unit: "",
        score:this.maxLevel === 1 ? 1 : 0,
        remark: ""
      };
      // 使用push方法添加新项，而不是重新赋值数组
      this.sciTaskIndicatorItemList.push(newItem);
    },

    /** 添加子指标项 */
    addChildIndicator(parentItem) {
      if (parentItem.itemLevel >= this.maxLevel) {
        this.$message.warning(`已达到最大层级深度 ${this.maxLevel}`);
        return;
      }

      const newItem = {
        itemId: this.generateItemId(),
        templateId: this.selectedTemplateId,
        parentId: parentItem.itemId,
        itemName: "",
        itemLevel: parentItem.itemLevel + 1,
        sortOrder: this.sciTaskIndicatorItemList.filter(item => item.parentId === parentItem.itemId).length + 1,
        isDeepestLevel: parentItem.itemLevel + 1 === this.maxLevel ? 1 : 0,
        indicatorNature: "",
        indicatorDirection:"",
        targetValue: "",
        unit: "",
        score: parentItem.itemLevel + 1 === this.maxLevel ? 1 : 0,
        remark: ""
      };
      // 使用push方法添加新项，而不是重新赋值数组
      this.sciTaskIndicatorItemList.push(newItem);
    },
    /** 生成唯一ID */
    generateItemId() {
      // return this.itemIdCounter++; // 返回当前值并递增
      return Date.now() + Math.floor(Math.random() * 1000);
    },

    /** 项目产出指标项删除按钮操作 */
     handleDeleteSciTaskIndicatorItem() {
      if (this.checkedSciTaskIndicatorItem.length == 0) {
        this.$modal.msgError("请先选择要删除的项目产出指标项数据");
        return;
      }

      // 获取要删除的项ID列表（包括子项）
      const idsToDelete = this.getDescendantIds(this.checkedSciTaskIndicatorItem);

      // 创建全新的数组，确保每个对象都是新引用
      const newArray = JSON.parse(JSON.stringify(
        this.sciTaskIndicatorItemList.filter(
          item => !idsToDelete.includes(item.itemId)
        )
      ));
      this.sciTaskIndicatorItemList = newArray;

      // 清空选中状态
      this.checkedSciTaskIndicatorItem = [];
    },

    /** 获取所有后代节点ID */
    getDescendantIds(selectedIds) {
      const allIds = [...selectedIds];

      const findChildren = (parentId) => {
        const children = this.sciTaskIndicatorItemList.filter(item => item.parentId === parentId);
        children.forEach(child => {
          if (!allIds.includes(child.itemId)) {
            allIds.push(child.itemId);
            findChildren(child.itemId);
          }
        });
      };

      selectedIds.forEach(id => findChildren(id));
      return allIds;
    },

    /** 复选框选中数据 */
    handleSciTaskIndicatorItemSelectionChange(selection) {
      this.checkedSciTaskIndicatorItem = selection.map(item => item.itemId);
    },


    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {

          // 验证指标项数据
          if (!this.validateIndicatorItems()) {
            return;
          }

          const taskId = this.form.id; // 来自数据库的真实ID
          const localId = this.form.localId || `local-${this.localIdCounter++}`;

          const taskData = {
            ...this.form,
            sciTaskIndicatorItemList: this.sciTaskIndicatorItemList,
            localId: localId
          };

          let index = -1;

          if (taskId) {
            // 来自API的任务：根据 id 查找并更新
            index = this.projectTaskList.findIndex(task => task.id === taskId);
          } else {
            // 本地任务：根据 localId 查找并更新
            index = this.projectTaskList.findIndex(task => task.localId === localId);
          }

          if (index !== -1) {
            // 存在：更新已有任务
            this.projectTaskList.splice(index, 1, taskData);
          } else {
            // 不存在：新增到表格底部
            this.projectTaskList.push(taskData);
          }

          this.submitLocalData();

          // 关闭弹窗并重置表单
          this.open = false;
          this.reset();
        }
      });
    },

    submitLocalData() {
    // 将当前 projectTaskList 发送给父组件
      this.$emit('update:taskData', this.projectTaskList);
    },

    /** 提交按钮 */
    // submitForm() {
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       // 验证指标项数据
    //       if (!this.validateIndicatorItems()) {
    //         return;
    //       }

    //       this.form.sciTaskIndicatorItemList = this.sciTaskIndicatorItemList;
    //       if (this.form.id != null) {
    //         updateProjectTask(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addProjectTask(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },

    /** 验证指标项数据 */
    validateIndicatorItems() {
      // 检查是否选择了模板
      if (!this.selectedTemplateId) {
        this.$message.error("请选择模板");
        return false;
      }

      // 检查是否有指标项
      if (!this.sciTaskIndicatorItemList || this.sciTaskIndicatorItemList.length === 0) {
        this.$message.error("请添加至少一个指标项");
        return false;
      }

      // 检查所有指标项的名称是否填写
      for (let i = 0; i < this.sciTaskIndicatorItemList.length; i++) {
        const item = this.sciTaskIndicatorItemList[i];
        if (!item.itemName) {
          this.$message.error(`第${i + 1}行指标名称不能为空`);
          return false;
        }

        // 仅验证最深层级的详细指标信息
        if (item.itemLevel === this.maxLevel) {
          if (!item.indicatorNature) {
            this.$message.error(`第${i + 1}行指标性质不能为空`);
            return false;
          }
          if (!item.indicatorDirection) {
            this.$message.error(`第${i + 1}行指标方向不能为空`);
            return false;
          }
          if (!item.targetValue) {
            this.$message.error(`第${i + 1}行指标目标值不能为空`);
            return false;
          }
          if (!item.unit) {
            this.$message.error(`第${i + 1}行指标单位不能为空`);
            return false;
          }
          if (!item.score) {
            this.$message.error(`第${i + 1}行指标分数不能为空`);
            return false;
          }
        }
      }

      return true;
    },

    /** 删除按钮操作 */
    // handleDelete(row) {
    //   const ids = row.id || this.ids;
    //   this.$modal.confirm('是否确认删除项目任务编号为"' + ids + '"的数据项？').then(function() {
    //     return delProjectTask(ids);
    //   }).then(() => {
    //     this.getList();
    //     this.$modal.msgSuccess("删除成功");
    //   }).catch(() => {});
    // },


    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除项目任务名"' + row.taskName + '"的数据项？')
      .then(() => {
        // 从 projectTaskList 中移除对应行
        const index = this.projectTaskList.indexOf(row);
        if (index !== -1) {
          this.projectTaskList.splice(index, 1); // 删除指定行
        }
        this.submitLocalData();
      })
      .catch(() => {
        // 用户取消删除
      });
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('system/projectTask/export', {
        ...this.queryParams
      }, `projectTask_${new Date().getTime()}.xlsx`)
    },


    // 构建树形数据结构
    buildTreeData(items) {
      if (!items || items.length === 0) {
        return [];
      }

      // 创建映射以便快速查找节点
      const nodeMap = new Map();
      const roots = [];

      // 初始化所有节点，确保有children属性
      items.forEach(item => {
        // 如果还没有children属性，则添加
        if (!item.hasOwnProperty('children')) {
          this.$set(item, 'children', []);
        } else {
          // 清空children，因为我们要重新构建树
          item.children = [];
        }
        nodeMap.set(item.itemId, item);
      });

      // 构建父子关系
      items.forEach(item => {
        const parentId = item.parentId;
        if (!parentId || parentId === "0" || !nodeMap.has(parentId)) {
          roots.push(item);
        } else {
          const parent = nodeMap.get(parentId);
          if (parent) {
            parent.children.push(item);
          }
        }
      });

      return roots;
    },
  }
};
</script>
